package com.springcloud.authentication.core.redis;

import java.lang.reflect.Method;
import java.time.Duration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.springcloud.authentication.common.RedisUtil;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
	private static Logger logger = LogManager.getLogger(RedisConfig.class);

	@Autowired
	@Lazy
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	@Lazy
	private RedisTemplate<Object,Object> redisTemplate;


	//缓存管理器
	/*@Bean
	public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofHours(1)) // 设置缓存有效期一小时
				.disableCachingNullValues();

		RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
				.cacheDefaults(config)
				.transactionAware()
				.build();
		return redisCacheManager;
	}*/


	/**
	 * 自定义生成redis-key
	 */
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object o, Method method, Object... objects) {
				StringBuilder sb = new StringBuilder();
				sb.append(o.getClass().getName()).append(".");
				sb.append(method.getName()).append(".");
				for (Object obj : objects) {
					sb.append(obj.toString());
				}
				logger.info("keyGenerator=" + sb.toString());
				return sb.toString();
			}
		};
	}



	/**
	 * 注入封装RedisTemplate
	 * @throws
	 */
	@Bean(name = "redisUtil")
	public RedisUtil redisUtil() {
		RedisUtil redisUtil = new RedisUtil();
		redisUtil.setRedisTemplate(redisTemplate);
		return redisUtil;
	}



}
